package by.bsuir.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import org.hibernate.Session;

import by.bsuir.entity.Node;
import by.bsuir.entity.NodePers;
import by.bsuir.util.HibernateUtil;

public class NodeServicePostgres implements NodeService {

    public void save(Node node) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(bos);
            out.writeObject(node);
            byte[] nodeBytes = bos.toByteArray();
            out.close();
            bos.close();
            NodePers nodePers = new NodePers(1L, nodeBytes);
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.update(nodePers);
            session.getTransaction().commit();
            session.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public Node read(Long id) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            NodePers nodePers = (NodePers) session.get(NodePers.class, 1L);
            session.close();
            ByteArrayInputStream bis = new ByteArrayInputStream(
                    nodePers.getNode());
            ObjectInput in;
            in = new ObjectInputStream(bis);
            Node node = (Node) in.readObject();
            bis.close();
            in.close();
            return node;
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return null;
    }

}
